import { SettingsService } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  SocialService,
  SocialOpenType,
  TokenService,
  DA_SERVICE_TOKEN,
} from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { environment } from '@env/environment';
import { StartupService } from '@core/startup/startup.service';
import { CacheService } from '@core/routes-services/cache.service';
import { LoginService } from '@core/routes-services/login.service';
import { CurrUserService } from '@core/routes-services/Observer-service/curr-user.service';
import { CurrUserModel } from '@core/routes-services/Observer-service/curr-user.model';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnInit, OnDestroy {
  form: FormGroup;
  error = '';
  type = 0;
  loading = false;
  currUser:CurrUserModel=  new CurrUserModel(null,null,null);
  constructor(
    fb: FormBuilder,
    private router: Router,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private settingsService: SettingsService,
    private socialService: SocialService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private startupSrv: StartupService,
    private cacheService: CacheService,
    private loginService: LoginService,
    private currUserService: CurrUserService,
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(3)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  ngOnInit(): void {
    this.currUserService.currUserChange.subscribe((currUserModel) => {
      this.currUser = currUserModel;
    });
  }
  // region: fields

  get userName() {
    return this.form.controls.userName;
  }
  get password() {
    return this.form.controls.password;
  }
  get mobile() {
    return this.form.controls.mobile;
  }
  get captcha() {
    return this.form.controls.captcha;
  }

  // endregion

  switch(ret: any) {
    this.type = ret.index;
  }

  // region: get captcha

  count = 0;
  interval$: any;

  getCaptcha() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) clearInterval(this.interval$);
    }, 1000);
  }

  // endregion

  submit() {
    this.error = '';
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) return;
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) return;
    }
    this.loading = true;
    this.loginService.login({'name': this.userName.value, 'password': this.password.value}).then((resp) => {
      console.log(resp);
      let authToken = resp.headers.get('Authorization');
      this.cacheService.setTokenInfo(authToken);
      let id = resp.headers.get('X-Custom-header-id');
      let name = resp.headers.get('X-Custom-header-name');
      let role = resp.headers.get('X-Custom-header-role');
      let currUser = new CurrUserModel(id,name,role);
      this.currUserService.setCurrUser(currUser);
      this.cacheService.setCurrUserInfo(currUser);
      this.router.navigate(['/']);

      //后端springboot 对应配置实现corsfilter
      /*
      * import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AjaxCorsFilter extends CorsFilter {

    public AjaxCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        List<String> allowedHeaders = Arrays.asList("*");
        List<String> exposedHeaders = Arrays.asList("Authorization", "X-Custom-header-id", "X-Custom-header-name", "X-Custom-header-role");
        List<String> allowedMethods = Arrays.asList("*");
        List<String> allowedOrigins = Arrays.asList("*");
        corsConfig.setAllowedHeaders(allowedHeaders);
        corsConfig.setAllowedMethods(allowedMethods);
        corsConfig.setAllowedOrigins(allowedOrigins);
        corsConfig.setExposedHeaders(exposedHeaders);
        corsConfig.setMaxAge(36000L);
        corsConfig.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
        return source;
    }
}
       */


      // this.currUserService.setCurrUser(new CurrUserModel(1,'添加','admin_role'));
      // this.cacheService.setCurrUserInfo({id: 1, name: '添加', role: 'admin_role'});
      // this.router.navigate(['/']);
      // this.cacheService.setTokenInfo(resp.item.token);
      // this.tokenService.set({
      //       token: resp.item.token,
      //     });
      // this.loginService.getUserInfo().then((user) => {
      //   console.log(user);
      // this.cacheService.setCurrUserInfo(user);
      // const currUser = new CurrUserModel(user.id, user.name, user.role);
      // this.currUserService.setCurrUser(currUser);
      // this.router.navigate(['/auth-guard']);
      // });
      this.loading = false;
    }, (error) => {// 后台验证错误再根据具体错误指定 control dialog
      this.loading = false;
      console.log(error);
      this.msg.error(error.message ? error.message : error.error);
    });

    // mock http
    // this.loading = true;
    // setTimeout(() => {
    //   this.loading = false;
    //   if (this.type === 0) {
    //     if (
    //       this.userName.value !== 'admin' ||
    //       this.password.value !== '888888'
    //     ) {
    //       this.error = `账户或密码错误`;
    //       return;
    //     }
    //   }
    //
    //   // 清空路由复用信息
    //   this.reuseTabService.clear();
    //   // 设置Token信息
    //   this.tokenService.set({
    //     token: '123456789',
    //     name: this.userName.value,
    //     email: `cipchk@qq.com`,
    //     id: 10000,
    //     time: +new Date(),
    //   });
    //   // 重新获取 StartupService 内容，若其包括 User 有关的信息的话
    //   // this.startupSrv.load().then(() => this.router.navigate(['/']));
    //   // 否则直接跳转
    //   this.router.navigate(['/']);
    // }, 1000);
  }


  // endregion

  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }

}
